# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         module.py
# Description:
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2019/11/18 17:00
# -------------------------------------------------------------------------------
from rest_framework import status
from rest_framework.mixins import UpdateModelMixin, DestroyModelMixin
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet, GenericViewSet

from QAPlatform.mixins import CustomCreateModelMixin
from apps.BasicAuthService.models import Role
from apps.HttpAutoTestService.filters import ModuleNameFilter
from apps.HttpAutoTestService.models import Module, Api
from apps.HttpAutoTestService.serializers import ModuleSerializer, ModuleNameListSerializer

__all__ = ['ModuleNameListViewSet', 'ModuleViewSet']


class ModuleNameListViewSet(ReadOnlyModelViewSet):
    """
    模块名称列表
    """
    serializer_class = ModuleNameListSerializer
    filter_class = ModuleNameFilter
    pagination_class = None

    def get_queryset(self):
        user = self.request.user
        modules = Module.objects.filter(is_deleted=False).order_by('create_time').values('id', 'name', 'parent',
                                                                                         'project', 'is_system',
                                                                                         'remark')
        if not Role.objects.filter(code='SUPERADMIN', user=user, is_deleted=False):
            modules = modules.filter(project__members=user).distinct()
        return modules


class ModuleViewSet(CustomCreateModelMixin, UpdateModelMixin, DestroyModelMixin, GenericViewSet):
    """
    模块创建、更新、删除
    """
    queryset = Module.objects.filter(is_deleted=False)
    serializer_class = ModuleSerializer

    def destroy(self, request, *args, **kwargs):
        id = kwargs.get('pk')
        module = Module.objects.filter(id=id, is_system=False).first()
        if module:
            module.is_deleted = True
            module.save()

            # 获取项目内置模块
            default_module = Module.objects.filter(project_id=module.project_id, is_system=True,
                                                   is_deleted=False).first()
            Api.objects.filter(module_id=id, is_deleted=False).update(module=default_module)
        return Response(status=status.HTTP_204_NO_CONTENT)
